--
-- Author: zhouzhanglin
-- Date: 2014-07-14 17:09:13
--
local EventDispatcher = class("EventDispatcher")

function EventDispatcher:ctor()
	self._eventArray = {} --对当前类的侦听 事件
end

function EventDispatcher:addEventListener( eventType,listener,target )
	assert(type(eventType)=="string","eventType必须为字符串")
	assert(type(listener)=="function","listener必须为function")

	if self._eventArray[eventType] ~= nil then
        self._eventArray[eventType][#self._eventArray[eventType]+1] = {listener = listener , target = target}
	else
        self._eventArray[eventType]= { {listener=listener,target=target} }
	end
end

function EventDispatcher:removeEventListener(eventType,listener)
	assert(type(eventType)=="string","eventType必须为字符串")
	assert(type(listener)=="function","listener必须为function")

	local listeners =  self._eventArray[eventType]
	if  listeners ~= nil then
		for i,v in ipairs(listeners) do
			if v.listener==listener then
				table.remove(listeners,i)
				if #listeners==0 then
					self._eventArray[eventType] = nil 
				end
			end
		end
	end
end

function EventDispatcher:hasEventListener(eventType,listener)
	assert( type(eventType)=="string","eventType必须为字符串")
    local listeners = self._eventArray[eventType]
	if listeners~= nil then
	   if listener~=nil then
            for _,v in ipairs(listeners) do
                if v.listener==listener then
                    return true
                end
            end
            return false
	   else
		   self._eventArray[eventType] = nil
	   end
	   return true
	end
	return false
end

function EventDispatcher:removeAllListeners()
	self._eventArray = nil
    self._eventArray={}
end


function EventDispatcher:dispatchEvent(event,target)
	local listeners = self._eventArray[event.type] 
    if listeners~=nil then
        event.target = target
        for _,listener in ipairs(listeners) do
            listener.listener(listener.target,event)
	    end
	end
end


function EventDispatcher:dispose()
    self._eventArray=nil
end


return EventDispatcher